package top.tenebrous.yzl.im.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import top.tenebrous.yzl.im.enums.ChannelType;
import top.tenebrous.yzl.im.listener.RedisReceiverListener;

/**
 * @author yazhang6
 */
@Configuration
@EnableCaching
public class RedisConfiguration {

    /**
     *  redis消息监听器容器
     *  可以添加多个监听不同话题的redis监听器
     *  只需要把消息监听器和相应的消息订阅处理器绑定
     *  该消息监听器通过反射技术调用消息订阅处理器的相关方法进行一些业务处理
     */
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        // 可以添加多个messageListener，配置不同的交换机
        container.addMessageListener(listenerAdapter, new PatternTopic(ChannelType.SEND_CHANNEL.getValue()));
        container.addMessageListener(listenerAdapter, new PatternTopic(ChannelType.MESSAGE_CHANNEL.getValue()));
        container.addMessageListener(listenerAdapter, new PatternTopic(ChannelType.CLOSE_CHANNEL.getValue()));
        container.addMessageListener(listenerAdapter, new PatternTopic(ChannelType.CUSTOM_CHANNEL.getValue()));
        return container;
    }
 
    // 消息监听器适配器，绑定消息处理器，利用反射技术调用消息处理器的业务方法
    @Bean
    MessageListenerAdapter listenerAdapter(RedisReceiverListener receiver) {
        // 消息监听适配器
        return new MessageListenerAdapter(receiver, "onMessage");
    }
 
}